package com.demo.zookeeper;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

public class ZKGetData {
	private static ZooKeeper zk;
	final static CountDownLatch countDownLatch = new CountDownLatch(1);
	
	public static void nodeGetData(Stat stat) throws KeeperException, InterruptedException {
		if(stat != null) {
			final String path = "/dataNode";
			byte[] bytes = zk.getData(path, new Watcher() {
				
				public void process(WatchedEvent event) {
					if(event.getType() != Event.EventType.None) {
						try {
							byte[] data = zk.getData(path, false, null);
							String str = new String(data, Charset.defaultCharset());
							System.out.println(str);
							countDownLatch.countDown();
						} catch (KeeperException e) {
							e.printStackTrace();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					} else {
						try {
							byte[] data = zk.getData(path, false, null);
							String str = new String(data, Charset.defaultCharset());
							System.out.println(str);
							countDownLatch.countDown();
						} catch (KeeperException e) {
							e.printStackTrace();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}, null);
			String str = new String(bytes, Charset.defaultCharset());
			System.out.println(str);
			countDownLatch.await();
		}		
	}
	
	public static void main(String[] args) throws IOException, InterruptedException, KeeperException {
		zk = ZookeeperConnection.connect();
		String path = "/dataNode";
		Stat stat = zk.exists(path, true);
		ZKGetData.nodeGetData(stat);
		ZookeeperConnection.close();
	}
}
